package com.woniuxy.ticketauth.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.ticketauth.entity.Manager;
import com.woniuxy.ticketauth.jwt.Audience;
import com.woniuxy.ticketauth.jwt.JwtUtil;
import com.woniuxy.ticketauth.mapper.ManagerMapper;
import com.woniuxy.ticketauth.mapper.PermMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @ClassName DbRealm
 * @Description 自定义Realm，用于与数据库交互
 * @Author zx
 * @Date 2021-03-03 14:14:04
 * @Version 1.0
 */
public class DbRealm extends AuthorizingRealm {

    @Resource
    private ManagerMapper managerMapper;

    @Resource
    private PermMapper permMapper;

    @Resource
    private Audience audience;
    /**
     * 授权，获取用户的权限列表
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String jwt = principals.getPrimaryPrincipal().toString();
        int id = JwtUtil.getUserId(jwt, audience.getBase64Secret());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        permMapper.getPermsById(id).forEach(perm -> {
            info.addStringPermission(perm.getCode());
        });
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken =(UsernamePasswordToken)token;
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",upToken.getUsername());
        Manager manager = managerMapper.selectOne(queryWrapper);
        if (manager==null){
            throw new UnknownAccountException("账号："+upToken.getUsername()+"不存在");
        }

        return new SimpleAuthenticationInfo(manager,manager.getPwd(),getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }
}
